package com.cn.wanxi.filter;

import com.alibaba.fastjson.JSONObject;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter("/back/*")
public class MyFilter implements Filter {
    /**
     * 定时器的时候执行这里
     *
     * @param filterConfig
     * @throws ServletException
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    /**
     * 过滤器
     *
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

//        我们需要判断哪些访问后台的接口需要登录，如果已经登录，则可以进行后面的代码，否则，返回错误代码，或者跳转到登录页面
//        需要得到前端访问后台的接口：地址
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        //        1.乱码处理
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        String path = req.getServletPath();
//        String aa = req.getRequestURI();
//        System.out.println(path);
//        System.out.println(aa);
//        if (path.startsWith("/back/")) {
            String username = (String) req.getSession().getAttribute("username");
            if (username == null) {
                resp.getWriter().println(JSONObject.toJSONString("noLogin"));
            } else {
                filterChain.doFilter(req, resp);
            }
//        } else {
//            //        如果不需要拦截，则需要对接口地址进行放行
//            filterChain.doFilter(req, resp);
//        }

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
